<template>
    <el-row class="lives-news">
        <el-row>
            <el-col class="title">
                <h3>直播互动</h3>
            </el-col>
        </el-row>
        <el-row class="search-row">
            <el-form class="inline-form" :inline="true">
                <el-form-item>
                    <el-button type="primary" @click="showAddDialog"><i class="el-icon-plus el-icon--left"></i>发送消息</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="showExportPopup"><i class="el-icon-share el-icon--left"></i>导出</el-button>
                </el-form-item>
                <!-- <el-form-item>
                    <el-checkbox v-model="autoFresh">10秒自动更新</el-checkbox>
                </el-form-item> -->
            </el-form>
        </el-row>
        <el-row>
            <el-col>
                <el-table :data="messageList">
                    <el-table-column prop="messageId" label="消息ID" width="120px" align="center"></el-table-column>
                    <el-table-column prop="username" label="发送者账号" width="140px" align="center"></el-table-column>
                    <el-table-column prop="name" label="昵称" width="140px" align="center"></el-table-column>
                    <el-table-column label="管理员发送" width="120px" align="center">
                        <template slot-scope="scope">{{scope.row.admin ? '是': '否'}}</template>
                    </el-table-column>
                    <el-table-column label="发送时间" align="center">
                        <template slot-scope="scope">{{moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss')}}</template>
                    </el-table-column>
                    <el-table-column prop="content" label="内容" align="center">
                        <template slot-scope="scope">
                            <span v-html="formatChatText(scope.row.content)"></span>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" align="center">
                        <template slot-scope="scope">
                            <span :class="scope.row.passed?'passed':'unpassed'">{{scope.row.passed?'审核通过':'未审核'}}</span></template>
                    </el-table-column>
                    <el-table-column label="员工发送" align="center">
                        <template slot-scope="scope">
                            <span :class="(scope.row.salesman||scope.row.admin)?'salesman':''">{{scope.row.admin? '员工': (scope.row.salesman?'员工':'客户')}}</span></template>
                    </el-table-column>
                    <el-table-column label="审核" width="140px" align="center">
                        <template slot-scope="scope">
                            <span v-if="scope.row.passed">已审核</span>
                            <el-button type="primary" v-else size="small" @click="passMessage(scope.$index, scope.row)">通过</el-button>
                            <!-- 
                            <el-button type="danger" size="small" @click="deleteMsg(scope.$index, scope.row)">删除</el-button>
                             -->
                        </template>
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>
        <el-dialog title="发送消息" :visible.sync="addDialog" size="tiny" @close="cancelAddCategory" class="dialog">
                <el-form :model="msg" label-width="120px">
                    <el-form-item label="消息发送人">
                        <el-radio-group v-model="msg.name">
                            <el-radio label="主播老师">主播老师</el-radio>
                            <el-radio label="直播助理">直播助理</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="消息内容">
                        <div class="emoji-contain">
                            <div class="emoji-wrap" v-show="showEmoji">
                                <img v-for="(item,index) in emoji" :key="index" :src="'/static/qqFace/'+index+'.gif'" :alt="item" width="24" height="24" @click="addEmoji2Chat('['+item+']')" :title="item">
                            </div>
                            <i class="smile-o" @click="showEmoji=!showEmoji"></i>
                        </div>
                        <textarea class="textarea" v-model.trim="msg.content" placeholder="请输入聊天消息内容" ref="textarea"></textarea>
                    </el-form-item>
                </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelAddCategory">取 消</el-button>
                <el-button type="primary" @click="addCategory" :loading="addLoading">发 送</el-button>
            </div>
        </el-dialog>
        <!-- 分页 -->
        <el-row>
            <el-col class="pagination">
                <el-pagination @current-change="currentChange" :current-page="pageId" :page-size="pageSize" layout="total, prev, pager, next" :total="counts">
                </el-pagination>
            </el-col>
        </el-row>
        <el-dialog title="聊天信息导出" :visible.sync="exportDialog" size="tiny" @close="cancelDialog" class="dialog">
            <el-form label-width="120px">
                <el-form-item label="开始时间">
                    <el-date-picker
                      v-model="startTime"
                      :editable="false"
                      type="date"
                      placeholder="选择开始时间"
                      @change="formatStartDate">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间">
                    <el-date-picker
                      v-model="endTime"
                      :editable="false"
                      type="date"
                      placeholder="选择结束时间"
                      @change="formatEndDate">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelDialog">取消</el-button>
                <el-button type="primary" @click="exportsEXL" :loading="downloading">导出</el-button>
            </div>
        </el-dialog>
    </el-row>
</template>
<script>
import {
    getMessagesList,
    postMessage,
    messagePass,
    deleteMessageById
} from '@/api/api'
import {exportExcel} from '@/api/excel'
import emoji from '@/assets/js/emoji.js'
export default {
    data: function() {
        return {
            searchContent: '',
            pageId: 1,
            pageSize: 15,
            counts: 0,
            messageList: [],
            addDialog: false,
            msg: {
            	name: '主播老师',
                content: ''
            },
            addLoading: false,
            interVal: null,
            exportDialog: false,
            startTime: '',
            endTime: '',
            downloading: false,
            emoji: emoji,
            showEmoji: false
            // autoFresh: true
        }
    },
    created: function() {
        this.pageId = parseInt(this.$route.query.page) || 1;
        this.getMessage();
        this.interVal = setInterval(() => {
            this.getMessage();
        }, 10000)
    },
    mounted: function(){
        var _this = this;
        document.addEventListener('click', function(e) {
            var event = e || window.event;
            var target = event.target || event.srcElement;
            if (_this.showEmoji && target.className != 'smile-o') {
                _this.showEmoji = false;
            }
        }, false)
    },
    destroyed: function() {
        clearInterval(this.interVal)
        this.interVal = null;
    },
    methods: {
        //获取视频分类列表
        getMessage: function() {
            getMessagesList({params: {pageSize: this.pageSize, pageId: this.pageId}}).then(data => {
                console.log(data)
                this.counts = data.count;
                this.messageList = data.list;
            })
        },
        //搜索
        searchArticleByName: function() {
            this.getMessage();
        },
        //分页
        currentChange: function(val) {
            this.$router.push('?page=' + val)
            this.pageId = val;
            this.getMessage()
        },
        showAddDialog: function(){
            this.addDialog = true;
        },
        cancelAddCategory: function(){
            this.addDialog = false;
            this.msg = {
                content: '',
                name: '主播老师'
            }
        },
        addCategory: function(){
            postMessage(this.msg).then(res => {
                this.$message({
                    type: 'success',
                    message: '发送成功'
                });
                this.getMessage();
                this.cancelAddCategory()
            })
        },
        passMessage: function(index, row){
            // this.$confirm('确定要显示该条聊天信息?', '聊天审核', {
            //     confirmButtonText: '确定',
            //     cancelButtonText: '取消',
            //     type: 'warning'
            // }).then(() => {
                messagePass(row.messageId).then(() => {
                    this.getMessage();
                    this.$message({
                        type: 'success',
                        message: '操作成功!'
                    });
                })
            // }).catch(() => {
            //     this.$message({
            //         type: 'info',
            //         message: '取消操作'
            //     });
            // });
        },
        deleteMsg: function(index, row){
            this.$confirm('确定要删除该条聊天信息?', '删除聊天', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteMessageById(row.messageId).then(() => {
                    this.getMessage();
                    this.$message({
                        type: 'success',
                        message: '操作成功!'
                    });
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '取消操作'
                });
            });
        },
        showExportPopup: function(){
            this.exportDialog = true;
        },
        cancelDialog: function(){
            this.exportDialog = false;
            this.startTime = ''
            this.endTime = ''
        },
        chunkBlob: function(data){
            var blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'})
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = this.moment(this.startTime).format('YYYY年MM月DD日') + '-' + this.moment(this.endTime).format('YYYY年MM月DD日') + '聊天记录';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(link.href);
            this.downloading = false;
            this.cancelDialog()
        },
        exportsEXL: function(){
            if(this.downloading){
                this.$message({
                    type: 'error',
                    message: '正在导出中!'
                });
                return
            }
            this.downloading = !this.downloading;
            exportExcel({params: {start: this.startTime, end: this.endTime}}).then(res => {
                this.chunkBlob(res.data)
            }).catch(e=>{
                this.$message({
                    type: 'error',
                    message: '导出出错，请稍后再试！'
                });
                this.downloading = false;
                console.log(e)
            })
        },
        formatStartDate: function(val){
            var v = val + ' 00:00:00'
            this.startTime = new Date(v).getTime()
        },
        formatEndDate: function(val){
            var v = val + ' 23:59:59'
            this.endTime = new Date(v).getTime()
        },
        formatChatText: function(text) {
            if (!text) {
                return text;
            }

            text = text.replace(/\[[\u4E00-\u9FA5]{1,3}\]/gi, function(word) {
                var newWord = word.replace(/\[|\]/gi, '');
                var index = emoji.indexOf(newWord);
                var imgHTML = '';
                if (index < 0) {
                    return word;
                }

                var path = 'https://res.wx.qq.com/mpres/htmledition/images/icon';
                imgHTML = `<img width="24" height="24" style="vertical-align: middle;" title="${newWord}" src="${path}/emotion/${index}.gif" alt="${newWord}">`
                return imgHTML;
            });
            return text;
        },
        addEmoji2Chat: function(name) {
            var textDom = this.$refs.textarea;
            var cursorPos = 0; //光标位置
            if (document.selection) {
                // IE Support
                var selectRange = document.selection.createRange();
                selectRange.moveStart('character', -this.msg.content.length);
                cursorPos = selectRange.text.length;
            } else if (textDom.selectionStart || textDom.selectionStart == '0') {
                // Firefox support
                cursorPos = textDom.selectionStart;
            }
            if (cursorPos != this.msg.content.length) {
                //光标位置不是在最后
                var msgArr = this.msg.content.split(''); //分隔成数组
                msgArr.splice(cursorPos, 0, name) //在光标位置插入emoji
                this.msg.content = msgArr.join(''); //转回字符串
            } else {
                this.msg.content += name;
            }
            this.showEmoji = false;
        },

    }
}
</script>
<style scoped lang="scss">
.lives-news {
    .title {
        font-size: 12px;
        border-bottom: 1px solid #eaeaea;
        margin-bottom: 5px;
        h3 {
            display: inline-block;
            padding: 5px 0;
            margin: 0;
            font-weight: normal;
            color: #23b7e5;
            border-bottom: 1px solid #23b7e5;
        }
    }
}
.unpassed{
    color: #ff4949;
}
/*emoji*/

.emoji-contain {
    position: relative;
    padding: 5px;
}

.smile-o {
    display: block;
    width: 16px;
    height: 16px;
    background: url(../../assets/smile.png) no-repeat center center;
    background-size: cover;
    margin: 0 5px;
}

.emoji-wrap {
    width: 624px;
    position: absolute;
    bottom: 30px;
    left: 0;
    border: 1px solid #bdbdbd;
    z-index: 99;
    background-color: #fff;
}
.textarea {
    width: 100%;
    box-sizing: border-box;
    height: 150px;
    border: none;
    outline: 1px solid #bdbdbd;
    overflow: hidden;
    color: #a8a8a8;
    resize: none;
}
.salesman{
    color: #ff0000;
}
</style>